package com.zhuang.springbootnio.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolMonitor {

    // 定期监控线程池状态
    public static void monitorThreadPool(ExecutorService executor, String poolName) {
        Thread monitorThread = new Thread(() -> {
            while (true) {
                try {
                    if (executor instanceof ThreadPoolExecutor) {
                        ThreadPoolExecutor tp = (ThreadPoolExecutor) executor;
                        System.out.println("[" + poolName + "] 线程池监控:");
                        System.out.println("  活跃线程数: " + tp.getActiveCount());
                        System.out.println("  核心线程数: " + tp.getCorePoolSize());
                        System.out.println("  最大线程数: " + tp.getMaximumPoolSize());
                        System.out.println("  队列大小: " + tp.getQueue().size());
                        System.out.println("  已完成任务数: " + tp.getCompletedTaskCount());
                        System.out.println("  总任务数: " + tp.getTaskCount());
                        System.out.println("------------------------------------");
                    }
                    TimeUnit.SECONDS.sleep(30); // 每30秒监控一次
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });

        monitorThread.setDaemon(true);
        monitorThread.start();
    }

    // 优雅关闭线程池
    public static void shutdownThreadPool(ExecutorService executor, String poolName) {
        System.out.println("开始关闭线程池: " + poolName);
        executor.shutdown(); // 拒绝新任务，执行完已提交任务

        try {
            // 等待60秒让已提交任务完成
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow(); // 强制关闭
                System.out.println("强制关闭线程池: " + poolName);

                // 再等待30秒
                if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                    System.err.println("线程池关闭失败: " + poolName);
                }
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }

        System.out.println("线程池已关闭: " + poolName);
    }
}
